package ws

import (
	"zong-go/pkg/auth"
	"zong-go/pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

type WsServer struct {
	conn *websocket.Conn
}

// Server is a websocket handler
func (wss *WsServer) Server(c *gin.Context) {
	// change the reqest to websocket model
	conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
		if r.Method != "GET" {
			return false
		}
		if r.URL.Path != "/api/ws" {
			return false
		}
		headers := []string{c.Request.Header.Get("Sec-WebSocket-Protocol")}
		if len(headers) > 0 {
			for _, sub := range headers {
				if _, err := auth.ParseToken(sub); err != nil {
					return false
				}
			}
		}
		return true
	}, Subprotocols: []string{
		c.Request.Header.Get("Sec-WebSocket-Protocol"),
	}}).Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		response.ResponseNotFound(c)
		return
	}

	// websocket connect
	//client := &Client{ID: currentUser.Name, Socket: conn, Send: make(chan []byte)}
	client := &Client{ID: c.ClientIP(), Socket: conn, Send: make(chan []byte)}

	Manager.Register <- client

	go client.Read()
	go client.Write()

	wss.conn = conn
}

// TimeWriter 向连接到ws的客户端发送数据(每隔2秒发送一次)
func (wss *WsServer) TimeWriter(message string) {
	for {
		time.Sleep(time.Second * 2)
		wss.conn.WriteMessage(websocket.TextMessage, []byte(message))
	}
}
